<?php

namespace App\Controllers;

use App\models\Admin;
use App\BaseController;
use System\Core\Config;
use System\Core\Request;
use System\Core\Session;

class AdminController extends BaseController
{

    public function index()
    {
        if (Session::get('admin_logged')) {
            return $this->view('admin/index');
        } else {
            $this->redirect('admin/login');
        }
    }

    public function login()
    {
        $request = new Request();

        if ($request->isPost()) {
            $data = $request->post();

            $username = $data['username'];
            if (empty($username)) {
                $this->error('用户名不能为空');
            }
            $password = $data['password'];
            if (empty($password)) {
                $this->error('密码不能为空');
            }

            $admin =  new Admin();
            $res = $admin->findByUserName([
                'admin_name' => $username,
                'admin_pass' =>  md5($password . Config::get('app.salt'))
            ]);

            if (!$res) {
                return $this->error('登录失败');
            }
            if (!Session::get('admin_logged')) {
                Session::set('admin_logged', $res['admin_name']);
            }
            return $this->success('登录成功');
        } else {
            return $this->view('admin/login');
        }
    }

    public function logout(){
        if (Session::get('admin_logged')) {
            Session::remove('admin_logged');
        }
        $this->success('退出成功', 'admin/login');
    }

    public function register()
    {
        $request = new Request();

        if ($request->isPost()) {
            $data = $request->post();
            $csrf_token = $data['csrf_token'];

            if(Session::get('csrf_token') != $csrf_token) {
                return $this->error('表单过期');
            }

            $username = $data['username'];
            if (empty($username)) {
                $this->error('用户名不能为空');
            }
            $password = $data['password'];
            if (empty($password)) {
                $this->error('密码不能为空');
            }
            $repassword = $data['repassword'];
            if (empty($password)) {
                $this->error('确认密码不能为空');
            }

            if ($password != $repassword) {
                $this->error('两次密码不一致');
            }

            $admin =  new Admin();
            $res = $admin->create([
                'admin_name' => $username,
                'admin_pass' => md5($password . Config::get('app.salt'))
            ]);
            if (!$res) {
                return $this->error('注册失败');
            }
            return $this->success('注册成功');
        } else {
            return $this->view('admin/register');
        }
    }
}
